package fm.dongman.animefm.view.util;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * 相册的工具类方法
 * Created by Administrator on 2017/11/27.
 */

public class CameraGallaryHelper {
    public static final int CHOOSE_PHOTO = 1;
    /**
     * 4.4以上版本使用
     * @param data
     */
    public static String handLeImageOnKitkat(Intent data,Context mContext){
        String imagePath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(mContext,uri)){
            String docId=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection,mContext);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public+downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null,mContext);
            }
        }else if("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath=getImagePath(uri,null,mContext);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            imagePath=uri.getPath();
        }
        return imagePath;
    }

    /**
     * 4.4以下上版本使用
     * @param data
     */
    public static String handleImageBeforeKitKat(Intent data,Context mContext){
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null,mContext);
        return imagePath;
    }

    public static Bitmap  displayImage(String imagePath,Context mContext) {
        Bitmap bitmap=null;
        if(imagePath !=null){
            bitmap= BitmapFactory.decodeFile(imagePath);
        }else {
            ToastHelper.getInstance(mContext).showError("获取图片失败");
        }
        return bitmap;
    }

     static String getImagePath(Uri uri, String selection,Context mContext) {
        String path=null;
        Cursor cursor=mContext.getContentResolver().query(uri,null,selection,null,null);
        if(cursor !=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return  path;
    }

}

